import {
  area
} from "../../../js/modules/gloab";
import {
  util
} from '../../../js/util';
const componentBehavior = require('../../../js/common/ComponentBehavior')

Component({
  behaviors: [componentBehavior],
  lifetimes: {
    attached() {
      // 改为等待数据加载完成后在设置，防止异步导致数据拿不到的问题
      if(this.data.load){
        this.load_area().then(() => {
          this.set_default_area("", "", "")
        }).catch(() => {
          this.set_default_area("", "", "");
        })
      } else {
        this.load_area()
      }
    },
    detached() {
      // 在组件实例被从页面节点树移除时执行
    },
  },
  options: {
    multipleSlots: true // 在组件定义时的选项中启用多slot支持
  },
  /**
   * 组件的属性列表
   */
  properties: {
    isDefault:{
      type:Boolean,
      value:true
    },
    load:{
      type:Boolean,
      value:false
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    region: [],
    tree: [],
    multiArray: [[], [], []],
    multiIndex: [0, 0, 0],
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
   * 加载地区
   */
    load_area: function () {
      var that = this
      return new Promise((resolve) => {
        area.load(function (res) {
          that.setData({
            tree: res.Content
          })
          resolve()
        })
      })
    },
    /**
       * 设置默认选中项
       */
    set_default_area: function (province, city, area,callback,errorCallback) {
      let that = this, select_area = [];
      let { tree, multiIndex, multiArray,isDefault } = this.data;
      let defaultAddr={};
      defaultAddr.Province = province;
      defaultAddr.City = city;
      defaultAddr.Area = area;
      select_area = [province, city, area];
      if (province!=""&&city!=""&&area!=""){
        that.setDefaultCallBack(select_area, callback);
      }
      let first = 0, second = 0,third=0, isExist = false;
      multiArray[0] = [];
      multiArray[1] = [];
      multiArray[2] = [];
      // 循环所有的省
      for (let p in tree) {
        if (p == province) {
          multiIndex[0] = first;
          let pcs = tree[p];
          second = 0;
          // 找到对应的市进行赋值
          for (let c in pcs) {
            if (c == city) {
              multiIndex[1] = second;
              let cas = pcs[c];
              // 找到对应的区域进行循环
              third=0;
              for (let a in cas) {
                if (a == area) {
                  multiIndex[2] = third;
                  isExist = true;
                }
                multiArray[2].push(a);
                third++;
              }
              second++;
            }
            multiArray[1].push(c);
          }
        }
        first++;
        multiArray[0].push(p);
      }
      that.setData({
        multiArray: multiArray,
        multiIndex: multiIndex
      }, function () {
        if (!isExist) {
          if(errorCallback && typeof(errorCallback)=='function'){
            errorCallback();
          }else{
            let obj = { detail: { value: 0, column: 0 } }
            that.bindMultiPickerColumnChange(obj, (defaultArea) => {
              if(isDefault){
              defaultAddr.Province = defaultArea[0];
              defaultAddr.City = defaultArea[1];
              defaultAddr.Area = defaultArea[2];
              that.setDefaultCallBack(defaultArea,callback);
              }
            });
          }
        }
      });

    },
    setDefaultCallBack(defaultAddr,callback){
      if (callback && typeof (callback)=="function"){
        callback(defaultAddr);
      }
    },
    /**
     * 点确定
     */
    bindMultiPickerChange: function (e) {
      let that = this;
      let { region, multiArray, tree } = this.data;
      region[0] = multiArray[0][e.detail.value[0]];
      region[1] = multiArray[1][e.detail.value[1]];
      region[2] = multiArray[2][e.detail.value[2]];
      let code = tree[region[0]][region[1]][region[2]];    
      this.setData({
        multiIndex: e.detail.value,
        region: region
      });
      this.triggerEvent("onColumnChangeEvent", { region: region, code: code });
    },
    /**
     * 每一列的滚动事件
     */
    bindMultiPickerColumnChange: function (e, callback) {
      let that = this;
      let { region, multiArray, multiIndex, tree } = this.data;
      let column = e.detail.column, row = e.detail.value;
      // console.log(column, row);
      multiIndex[column] = row;
      let all = tree, p_name = "", c_name="";

      switch (column) {
        // 切换省
        case 0:
          p_name = multiArray[0][row];
          multiArray[1] = new Array();
          multiArray[2] = new Array();
          region[0] = p_name;

          let cities = all[p_name];
          let def_city = "", ci = 0;
          // 获取当前少下面所有的市
          for (let c in cities) {
            multiArray[1].push(c);
            if (ci == 0) {
              let cas = cities[c];
              // 获取第一个市对应的区县
              for(let a in cas){
                multiArray[2].push(a);
              }
            }
            ci++;
          }

          region[1] = multiArray[1][0];
          region[2] = multiArray[2][0];
          multiIndex[0] = row;
          // 给定选中的位置
          multiIndex[1] = 0;
          multiIndex[2] = 0;
          break;
        // 市切换选择
        case 1:
          // 获取前面选中的省
          p_name = region[0];
          c_name = multiArray[1][row];
          multiArray[2] = new Array();
          region[1] = c_name;
          // 从数据中找到应省市的区县
          let areas = all[p_name][c_name]
          // console.log(p_name, c_name, all[p_name], areas);
          for (let a in areas) {
            multiArray[2].push(a);
          }

          region[2] = multiArray[2][0];
          multiIndex[2] = 0;
          break;
        // 地区选择
        case 2:
          var area_name = multiArray[2][row];
          region[2] = area_name;
          multiIndex[2] = row;
          break;
      }

      that.setData({
        region: region,
        multiArray: multiArray,
        multiIndex: multiIndex
      }, () => {
        if (callback && typeof (callback)) {
          callback(region);
        }

      });

    },
    getCodeByAddress(province, city, area){
      let {tree } = this.data;
      if (province) {
        province = province.replace('省', '').replace('市', '').replace('自治区', '').replace('特别行政区', '');
      }
      if (city && city.indexOf('市辖区') == -1) {
        city = city.replace('市', '');
      }
      let p_dic = tree[province],c_dic,a_dic;
      if (p_dic == undefined) return { code:""};
      let code="";
      let c_keys = Object.keys(p_dic), a_keys;
      //省存在时
      if (c_keys.length>0){
        a_dic = p_dic[city];
        //市存在时
        if (a_dic != undefined) {
          code = a_dic[area]
        }
        if (code == "" || code == undefined) {
          city = c_keys[0];
          a_dic = p_dic[c_keys[0]];
          a_keys = Object.keys(a_dic);
          code = a_dic[a_keys[0]];
          area = a_keys[0];
        }

      }
      else {
        city = c_keys[0];
        a_dic = p_dic[c_keys[0]];
        a_keys = Object.keys(a_dic);
        code = a_dic[a_keys[0]];
        area = a_keys[0];
      }
      console.log('picker-addr-getCodeByAddress', province, city, area, code);
      return { province: province, city: city, area: area, code: code };
    }
  }
})
